//
//  QDMetroCodeManager.m
//  QDMetroClient
//
//  Created by YueWen on 2019/2/26.
//  Copyright © 2019 YueWen. All rights reserved.
//

#import "QDMetroCodeManager.h"
#import "RITLQRCodeMaker.h"
#import "JX_GCDTimerManager.h"
#import "QDMetroClient-Swift.h"
#import <CoreBluetooth/CoreBluetooth.h>

#pragma mark - 蓝牙设备

#define SERVICE_UUID1        @"0D18"
#define SERVICE_UUID2        @"0A18"
//中软
#define SERVICE_UUID3        @"0D19"
#define SERVICE_UUID4        @"0A19"
//福田
#define SERVICE_UUID5        @"0D20"
#define SERVICE_UUID6        @"0A20"
//华腾
#define SERVICE_UUID7        @"0D21"
#define SERVICE_UUID8        @"0A21"

//=====

#define SERVICE_UUID11        @"180D"
#define SERVICE_UUID12        @"180A"
//中软
#define SERVICE_UUID13        @"190D"
#define SERVICE_UUID14        @"190A"
//福田
#define SERVICE_UUID15        @"200D"
#define SERVICE_UUID16        @"200A"
//华腾
#define SERVICE_UUID17        @"210D"
#define SERVICE_UUID18        @"210A"


#define QDMetroCodeManagerForceTime (6)

@interface QDMetroCodeManager()<CBCentralManagerDelegate,CBPeripheralDelegate>

/// 负责监听蓝牙状态的中心设备管理器
@property (nonatomic, strong) CBCentralManager *centralManager;
/// 代理对象
@property (nonatomic, weak, readwrite)id<QDCodeDataManager>delegate;
/// 付款类型
@property (nonatomic, copy) NSString *channel;
/// 当前二维码
@property (nonatomic, copy) NSString *qrcode;
/// 记录时间戳
@property (nonatomic, assign)NSTimeInterval forceTime;
/// 是否存在支付方式
@property (nonatomic, assign) BOOL hasChannelTypes;

@end

@implementation QDMetroCodeManager

#pragma mark - <QDCodeManager>

- (instancetype)init {
    if (self = [super init]) {
        self.forceTime = 0;
    }
    return self;
}

- (void)setCodeDelegate:(id<QDCodeDataManager>)codeDelegate {
    _delegate = codeDelegate;
}


- (id<QDCodeDataManager>)codeDelegate {
    return _delegate;
}


- (void)setChannelType:(NSString *)channelType {
    _channel = channelType;
}


- (NSString *)channelType {
    return _channel;
}


- (void)setHasChannel:(BOOL)hasChannel {
    _hasChannelTypes = hasChannel;
}

- (BOOL)hasChannel {
    return self.hasChannelTypes;
}



/// uuid
- (NSArray <CBUUID *> *)cbUUIDs {
    
    return [@[SERVICE_UUID11,
             SERVICE_UUID12,
             SERVICE_UUID13,
             SERVICE_UUID14,
             SERVICE_UUID15,
             SERVICE_UUID16,
             SERVICE_UUID17,
             SERVICE_UUID18,
             
             SERVICE_UUID1,
             SERVICE_UUID2,
             SERVICE_UUID3,
             SERVICE_UUID4,
             SERVICE_UUID5,
             SERVICE_UUID6,
             SERVICE_UUID7,
             SERVICE_UUID8
             ] ritl_map:^id _Nonnull(NSString *uuid) {
                 return [CBUUID UUIDWithString:uuid];
             }];
}


//中心设备管理器
- (CBCentralManager *)centralManager {
    
    if (!_centralManager) {
        _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue() options:@{@"CBCentralManagerOptionShowPowerAlertKey":@false}];//不弹出系统默认框
    }
    return _centralManager;
}


#pragma mark - <CBCentralManagerDelegate>
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
    if (central.state == CBCentralManagerStatePoweredOn) {
        
        //如果已经开启了
        [JX_GCDTimerManager.sharedInstance checkExistTimer:@"QDMetro" completion:^(BOOL doExist) {
            if (!doExist && self.codeDelegate) {
                [self startRequestQRCode];//启用
            }
        }];
        
        return;
    }
    
    [self cancleRequest];
    //TODO: 更新为蓝牙关闭状态
    [self.codeDelegate codeManager:self failType:QDMetroHeaderErrorTypeOutBluetooth];
}


- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSArray * array       = advertisementData[@"kCBAdvDataServiceUUIDs"];
    CBUUID * uuid1        = array.firstObject;
    NSString * uuidString = [NSString stringWithFormat:@"%@",uuid1];
    NSDictionary * dic    = advertisementData[@"kCBAdvDataServiceData"];
    NSArray * keyArr      = dic.allKeys;
    NSArray * valueArr    = dic.allValues;
    NSString * key        = [NSString stringWithFormat:@"%@",keyArr.firstObject];
    NSString * value      = [NSString stringWithFormat:@"%@",valueArr.firstObject];
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"<>[]{}（#%-*+=_）\\|~(＜＞$%^&*)_+ "];
    NSString * hmutStr    = [[value componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString:@""];
    NSString * update     = [[key stringByAppendingString:hmutStr] uppercaseString];
    
    if (update.length < 34) {
        return;
    }
    
    if (![self isEmptyString:value]) {
        if (![self isEmptyString:self.qrcode]) {
            NSString * UPString = [NSString stringWithFormat:@"%@,%@",uuidString,update];
            
            //上报消息:
            [self updateOrderNotifyMessageWithQrCode:self.qrcode agm:UPString];
        }
    }
}


- (BOOL)isEmptyString:(NSString *)aStr {
    
    if (!aStr) { return YES; }
    if ([aStr isKindOfClass:[NSNull class]]) { return YES; }
    if (!aStr.length) { return YES; }
    
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    return !trimmedStr.length;
}



#pragma mark - <QDCodeManager>

- (void)becomeFirstControl {
    //打开蓝牙
    [self.centralManager scanForPeripheralsWithServices:self.cbUUIDs options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @false}];
}


/// 开始请求二维码
- (void)startRequestQRCode {
    [self startRequestQRCodeWithFireInstantly:true];
}


/// 开始请求二维码
- (void)startRequestQRCodeWithFireInstantly:(BOOL)fireInstantly {
    
    [JX_GCDTimerManager.sharedInstance scheduledDispatchTimerWithName:@"QDMetro" timeInterval:3 queue:dispatch_get_main_queue() repeats:true fireInstantly:fireInstantly action:^{
        //开始请求
        [self requestMetroCode];
    }];
}

/// 取消请求
- (void)cancleRequest {
    NSLog(@"关闭地铁二维码");
    [JX_GCDTimerManager.sharedInstance cancelTimerWithName:@"QDMetro"];//取消
}


- (void)resignFirstControl {
    
    [_centralManager stopScan];//关闭蓝牙
    _centralManager.delegate = nil;//关闭代理
    _centralManager = nil;
    
    self.codeDelegate = nil;
    [self cancleRequest];//取消计时器
}


- (NSString *)title {
    return @"二维码对准闸机口扫码进站";
}

- (NSArray<NSString *> *)titles {
    return @[/*@"乘车码设置",*//*@"使用帮助",*/@"自助补站"];
}

- (NSArray<NSString *> *)imageNames {
    return @[/*@"mc_pop_setting",*//*@"",*/@"mc_repair"];
}


#pragma mark - 网络请求

- (void)reloadForce {
    
    //针对时间戳进行对比
    if (NSDate.date.timeIntervalSince1970 - self.forceTime < QDMetroCodeManagerForceTime){
        NSLog(@"强制刷新被限制了!"); return;
    }
    
    self.forceTime = NSDate.date.timeIntervalSince1970;//记录时间
    [self cancleRequest];
    [self requestMetroCodeWithForce:true];
    NSLog(@"手动刷新！");
}

/// 请求地铁二维码
- (void)requestMetroCode {
    [self requestMetroCodeWithForce:false];
}


/// 请求二维码，是否强制刷新
- (void)requestMetroCodeWithForce:(BOOL)isForce {
 
    if (!self.hasChannelTypes){
        [self.codeDelegate codeManager:self failType:QDMetroHeaderErrorTypeOutPayType]; return;
    }
    
    if (self.channel.isEmpty) {
        [self.codeDelegate codeManager:self failType:QDMetroHeaderErrorTypeOutDefaultChannel]; return;
    }
    
    __weak typeof(self) weakSelf = self;
    
    [self requestMetroCodeWithChannelType:self.channelType force:isForce complete:^(NSString * _Nonnull qrcode, NSString * _Nonnull type) {
        
        //对二维码进行处理
        NSString *handerCode = qrcode.mutableCopy;
        NSData *base64 = [weakSelf dataWithHexString:handerCode];
        NSString *base64WithHex = [weakSelf base64Encode:base64];
        
        self.qrcode = qrcode;
        [self.centralManager scanForPeripheralsWithServices:weakSelf.cbUUIDs options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @NO}];
        
        
        NSLog(@"正在%@中,delegate = %@",self.centralManager.isScanning ? @"扫描" : @"关闭",self.centralManager.delegate);
        
        if (base64WithHex.length > 20) {//展示二维码
            
            NSString *title = [type containsString:@"出"] ? @"出站" : @"进站";
            
            [weakSelf.codeDelegate codeManager:weakSelf codeString:base64WithHex info:@{@"title" : [NSString stringWithFormat:@"将二维码对准闸机扫描口刷码%@",title],@"topTitle": [NSString stringWithFormat:@"地铁%@码",title]} image:[RITLQRCodeMaker makeQRCodeWithValue:base64WithHex size:202]];
            
            if (isForce){ //如果强制刷新，开启自动刷新模式
                [weakSelf startRequestQRCodeWithFireInstantly:false];
                NSLog(@"我是强制刷新的!");
            }
            
            return;
        }
        
        //错误
        [weakSelf.codeDelegate codeManager:weakSelf failType:QDMetroHeaderErrorTypeNetFail];
    }];
    
    NSLog(@"请求地铁二维码");
}


#pragma mark - 二维码的相关操作

- (NSData *)dataWithHexString:(NSString *)hexString {
    const char *chars = [hexString UTF8String];
    int i = 0;
    NSUInteger len = hexString.length;
    
    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;
    
    while (i < len) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }
    return data;
}


- (NSString *)base64Encode:(NSData *)data
{
    static char base64EncodingTable[64] = {
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    };
    NSInteger length = [data length];
    unsigned long ixtext, lentext;
    long ctremaining;
    unsigned char input[3], output[4];
    short i, charsonline = 0, ctcopy;
    const unsigned char *raw;
    NSMutableString *result;
    
    lentext = [data length];
    if (lentext < 1)
        return @"";
    result = [NSMutableString stringWithCapacity: lentext];
    raw = [data bytes];
    ixtext = 0;
    
    while (true) {
        ctremaining = lentext - ixtext;
        if (ctremaining <= 0)
            break;
        for (i = 0; i < 3; i++) {
            unsigned long ix = ixtext + i;
            if (ix < lentext)
                input[i] = raw[ix];
            else
                input[i] = 0;
        }
        output[0] = (input[0] & 0xFC) >> 2;
        output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
        output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
        output[3] = input[2] & 0x3F;
        ctcopy = 4;
        switch (ctremaining) {
            case 1:
                ctcopy = 2;
                break;
            case 2:
                ctcopy = 3;
                break;
        }
        
        for (i = 0; i < ctcopy; i++)
            [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];
        
        for (i = ctcopy; i < 4; i++)
            [result appendString: @"="];
        
        ixtext += 3;
        charsonline += 4;
        
        if ((length > 0) && (charsonline >= length))
            charsonline = 0;
    }
    return result;
}

@end
